/**
 * Copyright (C) 2010 Cloudfarming <info@cloudfarming.nl>
 *
 * Licensed under the Eclipse Public License - v 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.eclipse.org/legal/epl-v10.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.cloudfarming.client.area.plot;

import nl.cloudfarming.client.area.plot.pref.AreaCulturePreference;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import javax.swing.filechooser.FileFilter;
import nl.cloudfarming.client.util.ShapeFileCopier;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.openide.filesystems.FileChooserBuilder;
import org.openide.util.Cancellable;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.util.NbPreferences;

//FIXME this code looks like a mess, clean up
//TODO add copy of files to archive dir
public final class ShapeFilePicker {

    private static final String USER_HOME = "user.home";
    private boolean cancelled = false;
    //
    // the progress handle, creates a progress bar in the lower right corner of the screen
    private final ProgressHandle progressHandle = ProgressHandleFactory.createHandle("processing shape files", new Cancellable() {

        @Override
        public boolean cancel() {
            cancelled = true;
            progressHandle.finish();
            return cancelled;
        }
    });

    public void show() {

        String name = AreaCulturePreference.LAST_SHAPE_DIR.getValue();
        File userHome = (name.equals("")) ? new File(System.getProperty(USER_HOME)) : new File(name);
        //
        // creation of the file chooser
        File file = new FileChooserBuilder(NbBundle.getMessage(this.getClass(), "chooser.shape.directory"))
                .setTitle(NbBundle.getMessage(this.getClass(), "chooser.shape.title"))
                .setDefaultWorkingDirectory(userHome)
                .addFileFilter(new FileFilter() {

            @Override
            public boolean accept(File f) {
                String name = f.getName().toLowerCase();
                return f.isDirectory() || (f.isFile() && name.endsWith(".shp"));
            }

            @Override
            public String getDescription() {
                return "Shape file (*.shp)";
            }
        }).setApproveText(NbBundle.getMessage(this.getClass(), "chooser.shape.approve.text")).showOpenDialog();

        if (file == null){
            return;
        }

        try {
            // save the file path for next time window is opened
            AreaCulturePreference.LAST_SHAPE_DIR.saveValue(file.getPath());
            ShapeFileCopier copier = new ShapeFileCopier();


            StringBuilder sb = new StringBuilder(NbPreferences.root().get("user.dir", System.getProperty("user.dir")));
            sb.append("/");
            sb.append(AreaCulturePreference.SHAPE_FILE_ARCHIVE_DIR.getValue());
            String appDir = sb.toString();

            if (file.isDirectory()) {
                File destination = copier.copyDirectory(file, new File(appDir));

                progressHandle.start(destination.listFiles().length);

                if (destination.listFiles().length < 1) {
//                    InputOutput io = IOProvider.getDefault().getIO("Task", true);
//                    io.getOut().println("Info message");
//                    io.getErr().println("error message");
//                    io.getOut().close();
//                    io.getErr().close();

                    throw new FileNotFoundException("no files found in " + destination.getAbsolutePath());
                } else {
                    for (File f : destination.listFiles()) {

                        if (f.getName().toLowerCase().endsWith(".shp")) {
                            ShapeFileProcessor processor = new ShapeFileProcessor(f);
                            processor.process();
                            progressHandle.progress(f.getName() + " processed", 1);
                        } else {
                            progressHandle.progress(1);
                        }
                    }
                }
            } else {
                progressHandle.start(1);
                File destination = copier.copyFile(file, new File(appDir));
                if (destination.getName().toLowerCase().endsWith(".shp")) {
                    ShapeFileProcessor processor = new ShapeFileProcessor(destination);
                    processor.process();
                    progressHandle.progress(destination.getName() + " processed", 1);
                }
            }


        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        } catch (NoSuchAlgorithmException ex) {
            Exceptions.printStackTrace(ex);
        } finally {
            progressHandle.finish();
        }
    }
}
